﻿using DotNetCore.CAP.Dashboard;
using Hangfire.Dashboard.BasicAuthorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;

namespace Hicap.QRCodeWarehouse.Core.Identity
{
    public class CapAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool LoginCaseSensitive { get; set; }
        public IEnumerable<BasicAuthAuthorizationUser> Users { get; set; }

        public bool Authorize(DashboardContext context)
        {
            if (context is CapDashboardContext capContext)
            {
                if (capContext.HttpContext.Request.Path.ToString().ToLower().Contains("health")) return true;

                string header = capContext.HttpContext.Request.Headers["Authorization"];
                if (!string.IsNullOrWhiteSpace(header))
                {
                    AuthenticationHeaderValue authenticationHeaderValue = AuthenticationHeaderValue.Parse(header);

                    if ("Basic".Equals(authenticationHeaderValue.Scheme, StringComparison.OrdinalIgnoreCase))
                    {
                        string[] strArray = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationHeaderValue.Parameter)).Split(':');
                        if (strArray.Length > 1)
                        {
                            string login = strArray[0];
                            string password = strArray[1];
                            if (!string.IsNullOrWhiteSpace(login) && !string.IsNullOrWhiteSpace(password) && Users.Any(user => user.Validate(login, password, LoginCaseSensitive)))
                                return true;
                        }
                    }
                }
                return Challenge(capContext.HttpContext);
            }

            return false;
        }

        private bool Challenge(HttpContext context)
        {
            context.Response.StatusCode = 401;
            context.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"CAP Dashboard\"");
            return false;
        }
    }
}